package Interfaces;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import lemar.ConexionHibernate;
import lemar.entidad.Proveedor;
import lemar.entidad.Usuario;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class ConsultarUsuario extends javax.swing.JPanel {
//Atributos para el uso de Hibernate
    private static SessionFactory sessionFactory = null;
        public ConsultarUsuario() {
        initComponents();
        //Se carga el comboBox Dinamicamente de la BD
        cargarComboBox();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cmbNombreUsuario = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        txtContraseña = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtTipoUsuario = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));
        setMaximumSize(new java.awt.Dimension(747, 435));
        setMinimumSize(new java.awt.Dimension(747, 435));
        setPreferredSize(new java.awt.Dimension(747, 435));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Consultar Datos De Usuario");

        jLabel2.setText("Nombre Del Usuario ");

        cmbNombreUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jSeparator1.setMaximumSize(new java.awt.Dimension(40, 10));
        jSeparator1.setMinimumSize(new java.awt.Dimension(40, 10));
        jSeparator1.setPreferredSize(new java.awt.Dimension(40, 10));

        jLabel3.setText("Contraseña");

        txtContraseña.setEditable(false);

        jLabel4.setText("Tipo de Usuario");

        txtTipoUsuario.setEditable(false);
        txtTipoUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTipoUsuarioKeyTyped(evt);
            }
        });

        jButton1.setText("Consultar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsUsuaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(176, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 406, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(cmbNombreUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addGap(28, 28, 28)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(61, 61, 61)))
                        .addGap(165, 165, 165))))
            .addGroup(layout.createSequentialGroup()
                .addGap(254, 254, 254)
                .addComponent(jLabel1)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(60, 60, 60)
                .addComponent(jLabel1)
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbNombreUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 137, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void txtTipoUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTipoUsuarioKeyTyped
        // SOLO NUMEROS
        char c;
        c=evt.getKeyChar();
        if(!(c<'0'||c>'9'))
            //if((car<'a' || car>'z') && (car<'A' || car>'Z')) evt.consume();
            evt.consume();
    }//GEN-LAST:event_txtTipoUsuarioKeyTyped

    private void btnConsUsuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsUsuaActionPerformed
        // TODO add your handling code here:
        String nombreUsuario = "";
        
        List<Usuario> usuario = null;
        
        //Se extrae el nombre del proveedor seleccionado
        nombreUsuario = cmbNombreUsuario.getSelectedItem().toString();
        
        if(nombreUsuario.equalsIgnoreCase("<--Seleccione Usuario-->")){
            JOptionPane.showMessageDialog(null,"Seleccione Nombre de Usuario","Selección de datos",JOptionPane.ERROR_MESSAGE);
        }
        else{
            
            //Chunche de Hibernate (Inicio de sesion de hibernate)
            Session session = null;
            //Cadena de seleccion de HQL
            String hql = "FROM lemar.entidad.Usuario AS usuario WHERE usuario.nombreUsuario = :nombreUsuario";
            try{
                try{
                    //Conexion a la BD
                    sessionFactory = ConexionHibernate.getSessionFactory();
                    //Apertura de la sesion
                    session = sessionFactory.openSession();
                    Transaction txt = session.beginTransaction();                                       
                    
                    //Extraccion de los datos del proveedor de la BD                    
                    Query query = session.createQuery(hql).setString("nombreUsuario", nombreUsuario);
                    
                    //Se extrae los registros del proveedor
                    usuario = query.list();
                    
                    //Se ponen los datos del usuario en los campos de texto para su respectiva consulta
                    
                    
                    txtContraseña.setText(usuario.get(0).getPassword());
                    txtTipoUsuario.setText(usuario.get(0).getTipoUsuario());
                    txt.commit();
                    
                     
                    }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            } finally {
                //Finalizacion de la sesion de hibernate
                session.close();
                }
        }
    
    }                                                

    //Metodo para cargar el comboBox dinamicamente de la BD
    private void cargarComboBox(){
        
        //Obtencion de todos los usuarios de la base de datos para llenar el comboBox de manera dinamica
        
        //Variable que contendra la lista de proveedores
        List<Usuario> listaUsuario = null;
        
        //Inicializacion de session de hibernate
        Session session = null;
        try{
            try{
                //Chunces que ocupa Hibernate
                sessionFactory = ConexionHibernate.getSessionFactory();
                session = sessionFactory.openSession();
                Transaction tx = session.beginTransaction();
                
                //Obteniendo de la BD todos los proveedores                
                listaUsuario = session.createQuery("from Usuario").list();
                
                //Creando un modelo de comboBox                
                DefaultComboBoxModel modeloCombo = new DefaultComboBoxModel();
                
                //Poniendole un mensaje de seleccion (Pirmer elemento)
                 modeloCombo.addElement("<--Seleccione un Usuario-->");
                
                //Llenando el modelo de comboBox con los nombres de los proveedores
                for(Usuario usuario : listaUsuario) 
                { 
                    modeloCombo.addElement(usuario.getNombreUsuario());                     
                }
                
                //Agregando el modelo del comboBox al comboBox del panel
                cmbNombreUsuario.setModel(modeloCombo);
                
            }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            }finally {
                session.close();
        }
        
    }//GEN-LAST:event_btnConsUsuaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cmbNombreUsuario;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField txtContraseña;
    private javax.swing.JTextField txtTipoUsuario;
    // End of variables declaration//GEN-END:variables
}
